package cn.rocky.prepare;


public class middleNode {

    public class ListNode {
        int val;
        ListNode next;

        ListNode() {
        }

        ListNode(int val) {
            this.val = val;
        }

        ListNode(int val, ListNode next) {
            this.val = val;
            this.next = next;
        }
    }

    /**
     * 返回中间节点
     */
    public ListNode middleNode(ListNode head) {
        ListNode slow = head,fast = head;
        while (fast != null && fast.next != null) {
            slow = slow.next;
            fast = fast.next.next;
        }
        return slow;
    }

    public ListNode middleNodeV1(ListNode head) {
        int n = 0;
        ListNode cur = head;
        while (cur != null) {
            cur = cur.next;
            n++;
        }
        int k = 0;
        cur = head;
        while (k < n >> 1) {
            k++;
            cur = cur.next;
        }
        return cur;
    }
}
